﻿using System.Net;
using System.Text;
using System.Text.Json;

namespace Translationassistant
{
    internal class YouDao
    {
        public static string Get(string str)
        {
            try
            {
                string url = "http://fanyi.youdao.com/translate?&doctype=json&type=AUTO&i=";

                //HttpGet(url + str);

                Root root = JsonSerializer.Deserialize<Root>(HttpGet(url + str))!;

                List<TranslateResultItemItem> ts = root.translateResult![0];

                TranslateResultItemItem translateResult = ts[0];

                return translateResult.tgt!;
            }
            catch (Exception)
            {
                return "Error";
            }

        }

        /// <summary>
        /// 数据获取
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string HttpGet(string url)
        {
            try
            {
                var client = new HttpClient();

                var response = client.GetAsync(new Uri(url)).Result;
                string t = response.Content.ReadAsStringAsync().Result;
                return t;
            }
            catch (Exception)
            {
                return "";
            }
        }
    }

    public class TranslateResultItemItem
    {
        /// <summary>
        /// 内容
        /// </summary>
        public string? src { get; set; }
        /// <summary>
        /// 结果
        /// </summary>
        public string? tgt { get; set; }
    }

    public class Root
    {
        /// <summary>
        /// 类型
        /// </summary>
        public string? type { get; set; }
        /// <summary>
        /// 错误代码
        /// </summary>
        public int errorCode { get; set; }
        /// <summary>
        /// 时间
        /// </summary>
        public int elapsedTime { get; set; }
        /// <summary>
        /// 结果
        /// </summary>
        public List<List<TranslateResultItemItem>>? translateResult { get; set; }
    }
}
